<template>
   <div class="app-container">
      <el-form :model="conditionForm" ref="queryRef" :inline="true" size="small" v-show="showSearch" label-width="68px">
         <el-form-item label="字典名称" prop="dictName">
            <el-input v-model="conditionForm.dictName" placeholder="请输入字典名称" clearable style="width: 240px"
               @keyup.enter="setCondition" />
         </el-form-item>
         <el-form-item label="字典类型" prop="dictType">
            <el-input v-model="conditionForm.dictType" placeholder="请输入字典类型" clearable style="width: 240px"
               @keyup.enter="setCondition" />
         </el-form-item>
         <el-form-item label="状态" prop="flags">
            <el-select v-model="conditionForm.flags" placeholder="字典状态" clearable style="width: 240px">
               <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item label="创建时间">
            <el-date-picker v-model="conditionForm.dateTimes" type="datetimerange" range-separator="至"
               start-placeholder="开始时间" end-placeholder="结束时间" :default-time="['00:00:00', '23:59:59']"
               style="width: 300px" />
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="setCondition">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" type="flex">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" size="medium"
               v-hasPermi="['system:dict:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate" size="medium"
               v-hasPermi="['system:dict:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete" size="medium"
               v-hasPermi="['system:dict:remove']">删除</el-button>
         </el-col>
         <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
               v-hasPermi="['system:dict:export']">导出</el-button>
         </el-col> -->
         <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-refresh" @click="handleRefreshCache" size="medium"
               v-hasPermi="['system:dict:remove']">刷新缓存</el-button>
         </el-col>
         <!-- <el-col> -->
         <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="selectData"></right-toolbar> -->
         <right-toolbar :showSearch="showSearch" @updateShowSearch="updateShowSearch"
            @queryTable="selectData"></right-toolbar>
         <!-- </el-col> -->

      </el-row>

      <el-table v-loading="tableLoading" :data="dataTable" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <!-- <el-table-column label="字典编号" align="center" prop="businessId" /> -->
         <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
         <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
               <router-link :to="'/sysAdmin/dictTypeDetail/' + scope.row.businessId" class="link-type">
                  <span>{{ scope.row.dictType }}</span>
               </router-link>
            </template>
         </el-table-column>
         <el-table-column label="状态" align="center" prop="flags">
            <template #default="scope">
               <dict-tag :options="sys_normal_disable" :value="scope.row.flags" />
            </template>
         </el-table-column>
         <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
         <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
               <span>{{ timeFormat(scope.row.createTime, 'y2s') }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:dict:edit']">修改</el-button>
               <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:dict:remove']">删除</el-button>
            </template>
         </el-table-column>
      </el-table>

      <!-- <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex" v-model:limit="queryParams.pageSize"
         @pagination="selectData" /> -->
      <el-pagination :total="pageInfo.total" background layout="total,sizes, prev, pager, next"
         :page-size="pageInfo.pageSize" :current-page="pageInfo.pageIndex" :page-sizes="[10, 20, 30, 40, 50]"
         @size-change="pageSizeChange" @current-change="selectData" style="float:right;"></el-pagination>
      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal="false" v-dialogDrag
         :close-on-press-escape="false" append-to-body>
         <el-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="字典名称" prop="dictName">
               <el-input v-model="form.dictName" placeholder="请输入字典名称" />
            </el-form-item>
            <el-form-item label="字典类型" prop="dictType">
               <el-input v-model="form.dictType" placeholder="请输入字典类型" />
            </el-form-item>
            <el-form-item label="状态" prop="flags">
               <el-radio-group v-model="form.flags">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">
                     {{ dict.label }}
                  </el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
               <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup lang="ts" name="Dict">
import useDictStore from '@/stores/dict'
import { listType, getType, delType, addType, updateType, refreshCache } from "@/requests/api/dict";
import { reactive, ref, toRefs, onMounted, Ref } from "vue";
import { useDict } from "@/hooks/useDict";
import { Message, MessageBox } from 'element-ui';
import RightToolbar from '@/components/RightToolbar.vue';
import { timeFormat, timeRangeTransform } from "@/utils/time"
import { conditionCommon, dictSearchformInit, dictTypeInit } from './data';
import { queryParamsInit } from '@/views/data';
import { usePagination } from '@/hooks/usePagination';
import DictTag from '@/components/DictTag.vue';
import { useReset } from '@/hooks/useReset';
import { useShowSearch } from '@/hooks/useShowSearch';
// const { proxy } = getCurrentInstance() as { proxy: Vue };
onMounted(() => {
   console.log('proxy', useDict);
})
const { showSearch, updateShowSearch } = useShowSearch();
// const { sys_normal_disable } = useDict("sys_normal_disable"); // 不用接口返回的字典数据，直接使用本地字典数据
const sys_normal_disable = ref(dictTypeInit)
const open = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");

const data = reactive({
   form: Object.assign({}, dictSearchformInit),
   // 条件查询的参数
   conditionForm: Object.assign({
      dateTimes: [],
   }, conditionCommon),
   queryParams: Object.assign({
      condition: Object.assign({
         "startTime": "",
         "endTime": ""
      }, conditionCommon)
   }, queryParamsInit),
   rules: {
      dictName: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
      dictType: [{ required: true, message: "字典类型不能为空", trigger: "blur" }]
   },
});

const { conditionForm, queryParams, form, rules } = toRefs(data);

/** 查询字典类型列表 */
const { dataTable,
   pageInfo,
   pageSizeChange,
   selectData, tableLoading } = usePagination(queryParams, listType)
/** 取消按钮 */
const cancel = () => {
   open.value = false;
   reset();
}
/** 搜索按钮操作 */
const setCondition = () => {
   console.log('查询条件', conditionForm.value)
   pageInfo.value.pageIndex = 1; // 最好重置pageIndex，因为有些数据很少，当处于非首页查询时容易误解
   if (queryParams.value.condition) {
      const { dateTimes, dictName, dictType, flags } = conditionForm.value
      queryParams.value.condition.flags = flags;
      queryParams.value.condition.dictName = dictName;
      queryParams.value.condition.dictType = dictType;
      timeRangeTransform(dateTimes, queryParams);
   }
   selectData();
}

/** 表单重置 */
const dictRef: Ref<any> = ref(null)
/** 重置按钮操作 */
const queryRef: Ref<any> = ref(null)
const { reset, resetQuery } = useReset({
   form,
   formInit: Object.assign({}, dictSearchformInit),
   formRef: dictRef,
   conditionForm,
   conditionFormRef: queryRef,
   request: setCondition
})
/** 新增按钮操作 */
const handleAdd = () => {
   reset();
   open.value = true;
   title.value = "添加字典类型";
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
   ids.value = selection.map((item: any) => item.businessId);
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}
/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
   open.value = true;
   // reset();
   const businessId = row.businessId || ids.value;
   // console.log('businessId', row.businessId, ids.value, businessId, '---', dataTable.value)
   const res = await getType(businessId);
   if (res && res.data) {
      form.value = res.data;
      // open.value = true;
      title.value = "修改字典类型";
   }
}
/** 提交按钮 */
const submitForm = () => {
   dictRef.value.validate((valid: any) => {
      if (valid) {
         if (form.value.businessId != undefined) {
            updateType(form.value).then(() => {
               Message.success("修改成功");
               open.value = false;
               selectData();
            });
         } else {
            addType(form.value).then(() => {
               Message.success("新增成功");
               open.value = false;
               selectData();
            });
         }
      }
   });
}
/** 删除按钮操作 */
const handleDelete = (row: any) => {
   const businessIds = row.businessId || ids.value;
   MessageBox.confirm('是否确认删除字典编号为"' + businessIds + '"的数据项？').then(() => {
      return delType(businessIds);
   }).then(() => {
      selectData();
      Message.success("删除成功");
   }).catch(() => { });
}
/** 导出按钮操作 */
// const handleExport = () => {
//    // window.open("http://localhost:8080/system/dict/type/export")
// }
/** 刷新缓存按钮操作 */
const handleRefreshCache = () => {
   refreshCache().then(() => {
      Message.success("刷新成功");
      useDictStore().cleanDict();
   });
}

selectData();
</script>
